package com.lzy.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * description: 字符串最大最小校验 <br>
 * date: 2023/11/12 下午10:29 <br>
 * author: lcc <br>
 * version: 1.0 <br>
 */
public class StringMinMaxValidator implements ConstraintValidator<StringMinMaxConstraint, String> {

    private StringMinMaxConstraint annotation;

    @Override
    public void initialize(StringMinMaxConstraint constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        try {
            int min = annotation.min();
            int max = annotation.max();
            if (getStrLength(s) >= min && getStrLength(s) <= max) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public int getStrLength(String s) throws Exception {
        byte[] bytes = s.getBytes("UTF-8"); // 将字符串转换为UTF-8编码的字节数组
        int byteLength = bytes.length;
        return byteLength;
    }
}
